package com.example.suuu.config.exception;

import com.example.suuu.model.result.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {
    /**
     * 自定义异常捕获
     */
    @ExceptionHandler(AppException.class)
    public ResultVo appException(AppException e) {
        return ResultVo.ResultVoFail(e.getMessage());
    }

    /**
     * 处理 json 请求体调用接口对象参数校验失败抛出的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo jsonParamsException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String s = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            String msg = String.format("%s%s;", fieldError.getField(), fieldError.getDefaultMessage());
            s += msg;
        }
        return ResultVo.ResultVoFail(s);
    }
    /**
     * 处理单个参数校验失败抛出的异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultVo ParamsException(ConstraintViolationException e) {
        String s = "";
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            s += violation.getMessageTemplate() + ";";
        }
        return ResultVo.ResultVoFail(s);
    }
    /**
     *  接口不存在跑出异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public ResultVo noHandlerFoundException(NoHandlerFoundException e) {
        return ResultVo.ResultVoFail(e.getMessage());
    }
    /**
     * @param e 未知异常捕获
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    public ResultVo exceptionHandler(Exception e){
        log.warn("发生了一个异常: "+e.getMessage());
        return ResultVo.ResultERROR();
    }
}
